package com.duoduo.common.api.help;

import com.duoduo.common.api.constants.Constant;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.security.MessageDigest;

public class Md5InnerUtil {
	
	private static final Logger logger = LoggerFactory.getLogger(Md5InnerUtil.class);
	private static final String DEFAULT_CHARSET = "UTF-8";
	
	public static String md5(String plainText) {
		return md5(plainText,DEFAULT_CHARSET, null, false);
	}

	public static String md5(String plainText, boolean toUpperCase) {
		return md5(plainText,DEFAULT_CHARSET, null, toUpperCase);
	}

	public static String md5(String plainText, String key, Integer num) {
		return md5(plainText + key,DEFAULT_CHARSET, num, false);
	}
	
	public static String md5(String plainText, String charset, boolean toUpperCase) {
		return md5(plainText, charset, null, toUpperCase);
	}

	public static String md5(String plainText, Integer num, boolean toUpperCase) {
		 return md5(plainText,DEFAULT_CHARSET, num, toUpperCase);
	}
	
	public static String md5(String plainText,String charset, Integer num, boolean toUpperCase) {
		String resultString = null;
		StringBuffer buf = new StringBuffer();
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			if(StringUtils.isNotBlank(charset)){
				md.update(plainText.getBytes(charset));
			}else{
				md.update(plainText.getBytes());
			}
			byte b[] = md.digest();
			int i;
			for (int offset = 0; offset < b.length; offset++) {
				i = b[offset];
				if (i < 0)
					i += 256;
				if (i < 16)
					buf.append("0");
				buf.append(Integer.toHexString(i));
			}

			if(num!= null && num == 16){
				resultString = buf.toString().substring(8, 24);
			} else {
				resultString = buf.toString();
			}

			md = null;
			buf = null;
		} catch (Exception e) {
			logger.error(Constant.EMPTY_STRING, e);
		}

		if (toUpperCase) {
			resultString = resultString.toUpperCase();
		}
		return resultString;
	}

}
